export interface UploadConfig {
  chunkSizeSmall: number; // bytes
  chunkSizeMedium: number; // bytes
  chunkSizeLarge: number; // bytes
  smallThreshold: number; // bytes
  largeThreshold: number; // bytes
  concurrency: number;
  maxRetries: number;
  adaptive: boolean;
}

const DEFAULT_CONFIG: UploadConfig = {
  chunkSizeSmall: 256 * 1024,     // 256KB
  chunkSizeMedium: 1 * 1024 * 1024, // 1MB
  chunkSizeLarge: 2 * 1024 * 1024,  // 2MB
  smallThreshold: 10 * 1024 * 1024, // <10MB -> small
  largeThreshold: 100 * 1024 * 1024, // >100MB -> large
  concurrency: 4,
  maxRetries: 3,
  adaptive: false,
};

export function getUploadConfig(): UploadConfig {
  try {
    const fromEnv = (window as any).__UPLOAD_CONFIG__ as Partial<UploadConfig> | undefined;
    const fromLocal = localStorage.getItem('react_chat_upload_config');
    const localCfg = fromLocal ? (JSON.parse(fromLocal) as Partial<UploadConfig>) : undefined;
    return { ...DEFAULT_CONFIG, ...fromEnv, ...localCfg } as UploadConfig;
  } catch {
    return { ...DEFAULT_CONFIG };
  }
}

export function setUploadConfig(partial: Partial<UploadConfig>) {
  const cfg = { ...getUploadConfig(), ...partial } as UploadConfig;
  localStorage.setItem('react_chat_upload_config', JSON.stringify(cfg));
}

export function pickChunkSize(fileSize: number, cfg: UploadConfig): number {
  if (fileSize < cfg.smallThreshold) return cfg.chunkSizeSmall;
  if (fileSize > cfg.largeThreshold) return cfg.chunkSizeLarge;
  return cfg.chunkSizeMedium;
}

